package com.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

@Component
public class CustomGatewayFilterFactory extends AbstractGatewayFilterFactory<CustomGatewayFilterFactory.Config> {

    public CustomGatewayFilterFactory() {
        super(CustomGatewayFilterFactory.Config.class);
    }

    /**
     * 读取配置文件的参数值，赋值到配置类中的属性上
     * */
    @Override
    public List<String> shortcutFieldOrder(){
        return Arrays.asList("name");
    }

    @Override
    public GatewayFilter apply(CustomGatewayFilterFactory.Config config) {
        System.out.println(config.getName());

        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                System.out.println("通过自定义工场创建的 GateWayFilter 前置");
                Mono<Void> filter = chain.filter(exchange);
                System.out.println("通过自定义工场创建的 GateWayFilter 后置");
                return filter;
            }
        };
    }

    public static class Config{
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Config(){}
    }
}
